import datetime
import paramiko
import requests


def get_beijing_time():
    # 使用世界时钟 API 获取当前时间（返回 UTC 时间）
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36'
    }
    url = "http://www.beijing-time.org/"
    response = requests.get(url, headers=headers)
    headers = response.headers
    # a=datetime.datetime.strftime()
    bjTime = datetime.datetime.strptime(headers.get('Date'), '%a, %d %b %Y %H:%M:%S %Z', )
    bjTime += datetime.timedelta(hours=8)
    return bjTime


def connect_ssh(host, port, username, password=None):
    # 服务器信息
    hostname = "172.26.101.143"
    port = 57522
    username = "root"
    private_key_path = r"C:\Users\xiaqq\.ssh\id_rsa"  # 例如 "~/.ssh/id_rsa"

    # 目标时间（格式：YYYY-MM-DD HH:MM:SS）
    new_time = '2025-04-08 16:45:58'

    # 连接服务器
    try:
        # 读取私钥
        private_key = paramiko.RSAKey(filename=private_key_path)

        # 创建 SSH 客户端
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 连接服务器
        client.connect(hostname, port, username, pkey=private_key)

        # 设置时间的命令（需要 root 权限）
        command = f"sudo date -s '{new_time}'"

        # 执行命令
        stdin, stdout, stderr = client.exec_command(command)

        # 提示用户输入 sudo 密码（如果需要）
        stdin.write("your_sudo_password\n")
        stdin.flush()

        # 输出执行结果
        print(stdout.read().decode())
        print(stderr.read().decode())

        # 关闭连接
        client.close()

    except Exception as e:
        print(f"发生错误: {e}")

if __name__ == '__main__':
    # print(get_beijing_time())
    connect_ssh(1,2,3)


